package org.peerjs.sig;

import org.peerjs.Utils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

class Ids {
    private static final Ids instance;

    static {
        instance = new Ids();
    }

    private final Set<String> ids = new HashSet<>();
    private final Map<Object, List<String>> allocates = new HashMap<>();

    private Ids() {

    }

    static String newId(Object owner, int len, String prefix) {
        return instance.generateId(owner, len, prefix);
    }

    static void revoke(Object owner) {
        List<String> ownerIds = instance.allocates.remove(owner);
        if (ownerIds != null) {
            synchronized (instance.ids) {
                ownerIds.forEach(instance.ids::remove);
            }
        }
    }

    //mc_of7xvm592u//
    //private String mc_of7xvm592u
    private String generateId(Object owner, int len, String prefix) {
        String id;
        synchronized (ids) {
            StringBuilder sb = new StringBuilder();
            sb.append(prefix);
            String token = Utils.randomAlphaNumeric(len);
            sb.append(token);
            id = sb.toString();
            ids.add(id);
        }
        if (!allocates.containsKey(id)) {
            allocates.put(owner, new LinkedList<>());
        }
        List<String> ownerIds = allocates.get(owner);
        if (ownerIds != null) {
            ownerIds.add(id);
        }
        return id;
    }

}
